import {View} from "@tarojs/components";
import DynamicForm, {FormConfig} from "@/components/DynamicForm";
import {useEffect, useMemo, useRef, useState} from "react";
import {InvoiceModel} from "@/common/apis/model";
import Taro from "@tarojs/taro";
import Utils from "@/utils/common";
import LogUtils from "@/utils/log";
import {
  invoiceDeleteApi,
  invoiceSaveApi,
  invoiceUpdateApi
} from "@/common/apis/home_datasource";
import {Button} from "@antmjs/vantui";
import LocalData from "@/common/local_data";

definePageConfig({
  navigationBarTitleText: '新增发票'
})
export default function AddFaPiao() {
  const invoiceFormConfigs: FormConfig[] = [
    {
      type: 'input',
      name: 'title', // Logical name for the company name field
      label: '公司名称',   // Label text (without the *)
      placeholder: '请填写公司名称',
      required: true,     // Set based on the asterisk
      rules: [{required: true, message: '请输入公司名称'}] // Basic validation rule
    },
    {
      type: 'input',
      name: 'no',       // Logical name for the tax ID field
      label: '税号',        // Label text (without the *)
      placeholder: '请填写税号',
      required: true,     // Set based on the asterisk
      rules: [{required: true, message: '请输入税号'}] // Basic validation rule
    },
    {
      type: 'input',
      name: 'bank',    // Logical name for the bank name
      label: '开户行',
      placeholder: '请填写开户行',
      required: false,    // No asterisk
      rules: []
    },
    {
      type: 'input',
      name: 'bankAccount', // Logical name for the bank account number
      label: '银行账号',
      placeholder: '请填写银行账号',
      required: false,
      rules: []
    },
    {
      type: 'textarea', // Although it could be long, the UI looks like a standard input cell
      name: 'address', // Logical name for the company address
      label: '单位地址',
      placeholder: '请填写单位地址',
      required: false,
      rules: []
    },
    {
      type: 'input',
      name: 'phone', // Logical name for the company phone
      label: '单位电话',
      placeholder: '请填写单位电话',
      required: false,
      inputType: LocalData.phoneInputType, // Suggests the keyboard type on mobile (if supported)
      rules: []
    },
    {
      type: 'switch',      // Matches the visual toggle switch
      name: 'isDefault',   // Logical boolean-like name
      label: '设为默认',
      required: false,
      rules: []
      // Switches typically don't have placeholders
    }
  ];

  const initValues = useRef<InvoiceModel>()

  const eventChannel = useRef<Taro.EventChannel | null>();

  const [showContent, setShowContent] = useState(false)


  useEffect(() => {
    const instance = Utils.getI();
    eventChannel.current = Utils.getChannel(instance);
    const params = Utils.getParamsByRouter(instance)
    if (params && params.data) {
      initValues.current = Utils.getObjectWithUrl<InvoiceModel>(params.data)
      Utils.setTitle('编辑发票')
      LogUtils.info(initValues.current)
    }
    setShowContent(true)
  }, []);


  // 提交回调
  const handleSubmit = (values) => {
    console.log('Form values:', values);
    const formData = {
      ...values,
      isDefault: values.isDefault ? 1 : 0
    };
    const api = initValues.current ? invoiceUpdateApi({
      ...formData,
      id: initValues.current.id
    }) : invoiceSaveApi(formData);
    api.then((res) => {
      LogUtils.info(`res=${res}`)
      if (res) {
        Utils.showOkToast('保存成功')
        if (eventChannel.current) {
          Utils.emit(eventChannel.current, 'invoiceAdded', true)
        }
        Utils.navigateBack()
      }
    })

    // 处理表单提交逻辑
  };

  // 错误回调
  const handleError = (errors) => {
    console.error('Form errors:', errors);
  };

  const data = useMemo(() => {
    if (!initValues.current) {
      return {}
    }
    const isDefault = initValues.current.isDefault === 1;
    return {
      ...initValues.current,
      isDefault: isDefault
    }
  }, [showContent]);

  return (
    <View className='form-page'>
      {
        showContent ? <DynamicForm
          formConfigs={invoiceFormConfigs}
          initialValues={data}
          onSubmit={handleSubmit}
          onError={handleError}
          submitText='保存发票'
          otherOperate={() => {
            return initValues.current ?
              <Button type='danger' plain hairline style={{margin: '24px 0 24px 24px'}} onClick={() => {
                if (initValues.current.id) {
                  Utils.modal('删除发票', '确定要删除该发票吗？', true, (ok) => {
                    if (ok) {
                      invoiceDeleteApi(initValues.current.id).then((res) => {
                        if (res) {
                          Utils.showOkToast('删除成功')
                          if (eventChannel.current) {
                            Utils.emit(eventChannel.current, 'invoiceAdded', true)
                            Utils.navigateBack({
                              delta: 1 // Go back one page
                            })
                          }
                        }
                      })
                    }
                  })
                }
              }}
              >删除地址</Button> : null
          }}
        /> : null
      }
    </View>
  );
}


